package com.jz.community.moduleshopping.timeLimit.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.RxTimeTool;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoadingCallback;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.goodsDetail.ui.GoodsDetailActivity;
import com.jz.community.moduleshopping.timeLimit.bean.LimitGoodsBean;
import com.jz.community.moduleshopping.timeLimit.bean.LimitTimeBean;
import com.jz.community.moduleshopping.timeLimit.presenter.TimeLimitPresenter;
import com.jz.community.moduleshopping.timeLimit.ui.adapter.LimitGoodsAdapter;
import com.jz.community.moduleshopping.timeLimit.ui.adapter.LimitTimeAdapter;
import com.jz.community.moduleshopping.timeLimit.utils.DividerItemLine;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RouterIntentConstant.TIME_LIMIT)
public class TimeLimitActivity extends BaseMvpActivity<TimeLimitView.View, TimeLimitPresenter> implements TimeLimitView.View, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R2.id.time_limit_back)
    ImageView timeLimitBack;
    @BindView(R2.id.time_limit_title)
    TextView timeLimitTitle;
    @BindView(R2.id.time_limit_toolbar)
    Toolbar timeLimitToolbar;
    @BindView(R2.id.time_limit_goods_rv)
    RecyclerView timeLimitGoodsRv;
    @BindView(R2.id.time_limit_rv)
    RecyclerView timeLimitRv;
    @BindView(R2.id.time_limit_parent)
    RelativeLayout timeLimitParent;
    @BindView(R2.id.ll_time_limit_time)
    LinearLayout llTimeLimitTime;

    View headView;

    private LoadService loadService;
    private View noDataView;//无数据显示
    private View loadingView;//加载显示

    private Disposable disposable_time;
    private Disposable disposable_count;

    private int oldPosition = 0;
    private String click_time;//控制点击“开抢提醒”的时间

    //head
    private TextView limitTitle;
    private CountdownView limitTimer;

    //服务器时间
    private long cur_time = 0;
    //全局的开始时间
    private String start_time;
    //全局的结束时间
    private String end_time;

    private LimitTimeAdapter adapter_time;
    private List<LimitTimeBean.EmbeddedBean.LimitTimeViewsBean> time_list = new ArrayList<>();

    private LimitGoodsAdapter adapter_goods;
    private List<LimitGoodsBean.EmbeddedBeanXX.ContentBeanX> goods_list = new ArrayList<>();

    private String cityId = "99999";

    private int page_time = 0;
    private int size_time = 10;
    private int totalPage_time = 0;

    private int page_goods = 0;
    private int size_goods = 10;
    private int totalPage_goods = 0;

    //用于显示倒计时的时间
    private long countTime;

    String status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_time_limit;
    }

    @Override
    protected TimeLimitPresenter createPresenter() {
        return new TimeLimitPresenter(this);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(timeLimitToolbar);
        timeLimitTitle.setText("限时购");

        cityId = BaseSpUtils.getInstance().getRegion(mActivity).getId() + "";

        loadService = LoadSir.getDefault().register(timeLimitParent, (Callback.OnReloadListener) v -> {
            if (loadService.getCurrentCallback() == ErrorCallback.class) {
                loadService.showCallback(LoadingCallback.class);
                mPresenter.initTimeData(cityId, page_time, size_time);
            }
        });

        loadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = (ImageView) view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);
        });

        loadService.setCallBack(EmptyCallback.class, (context, view) -> {
            ImageView mIvEmpty = (ImageView) view.findViewById(R.id.empty_img);
            TextView mTvEmpty = (TextView) view.findViewById(R.id.empty_tv);
            mIvEmpty.setImageResource(R.mipmap.empty_default);
            mTvEmpty.setText("暂无数据！");

        });

        loadService.setCallBack(LoadingCallback.class, (context, view) -> {
            ImageView mIvLoading = (ImageView) view.findViewById(R.id.loading_img);
            GlideApp.with(mActivity)
                    .asGif()
                    .load(R.drawable.loading_default)
                    .into(mIvLoading);

        });

        noDataView = getLayoutInflater().inflate(R.layout.view_empty, (ViewGroup) timeLimitGoodsRv.getParent(), false);

        ImageView empty_iv = (ImageView) noDataView.findViewById(R.id.empty_img);
        TextView empty_tv = (TextView) noDataView.findViewById(R.id.empty_tv);

        empty_iv.setImageResource(R.mipmap.empty_default);
        empty_tv.setText("暂无数据！");

        loadingView = getLayoutInflater().inflate(R.layout.view_loading, (ViewGroup) timeLimitGoodsRv.getParent(), false);

        ImageView loading_iv = (ImageView) loadingView.findViewById(R.id.loading_img);

        GlideApp.with(mActivity)
                .asGif()
                .load(R.drawable.loading_default)
                .into(loading_iv);
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        initRecyclerView();
        mPresenter.initTimeData(cityId, page_time, size_time);

    }

    private void initRecyclerView() {
        headView = LayoutInflater.from(mActivity).inflate(R.layout.module_shopping_head_time_limit, (ViewGroup) timeLimitGoodsRv.getParent(), false);

        //Time-RecyclerView
        LinearLayoutManager time_layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false);
        timeLimitRv.setHasFixedSize(true);
        timeLimitRv.setFocusable(false);
        timeLimitRv.setLayoutManager(time_layoutManager);
        adapter_time = new LimitTimeAdapter(R.layout.module_shopping_item_limit_time, time_list);
        timeLimitRv.setAdapter(adapter_time);

        //head
        limitTitle = headView.findViewById(R.id.head_limit_title);
        limitTimer = headView.findViewById(R.id.head_limit_count);
        llTimeLimitTime.addView(headView);

        //Time-Goods-RecyclerView
        LinearLayoutManager goods_layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
        timeLimitGoodsRv.setHasFixedSize(true);
        timeLimitGoodsRv.setFocusable(false);
        timeLimitGoodsRv.setLayoutManager(goods_layoutManager);
        timeLimitGoodsRv.addItemDecoration(new DividerItemLine(mActivity,
                DividerItemLine.VERTICAL));
        adapter_goods = new LimitGoodsAdapter(R.layout.module_shopping_item_home_list_time, goods_list);
        timeLimitGoodsRv.setAdapter(adapter_goods);
        adapter_goods.setOnLoadMoreListener(this, timeLimitGoodsRv);
        adapter_goods.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画

        adapter_time.setOnItemClickListener((adapter, view, position) -> {
            if (position != oldPosition) {
                adapter_time.change(oldPosition, position);
                oldPosition = position;
                adapter_time.notifyDataSetChanged();
                page_goods = 0;
                status = adapter_time.getData().get(position).getStatus();
                mPresenter.initGoodsData(cityId, adapter_time.getData().get(position).getLimitedStartTime(), adapter_time.getData().get(position).getLimitedStopTime(), page_goods, size_goods);
            }
        });

        adapter_goods.setOnItemClickListener((adapter, view, position) -> {
            if (!RxDataTool.isNullString(adapter_goods.getData().get(position).get_links().getSelf().getHref())) {
                Intent intent = new Intent(mActivity, GoodsDetailActivity.class);
                intent.putExtra("url", adapter_goods.getData().get(position).get_links().getSelf().getHref());
                startActivity(intent);
            }

        });

        adapter_goods.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tx_flash_bt) {
                if (adapter_goods.getData().get(position).getStatus().equals("1")) {
                    //未开抢
                    if (BaseUserUtils.getIsLogin(mActivity)) {
                        Logger.e("开始时间-点击" + click_time);
                        if (!RxDataTool.isNullString(adapter_goods.getData().get(position).getId())) {
                            showLoading();
                            long gid = Long.parseLong(adapter_goods.getData().get(position).getId());
                            mPresenter.sendTips(gid, adapter_goods.getData().get(position).getLimitedStartTime());
                        }
                    } else {
                        WpToast.s(mActivity, "您需要先登录");
                        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN);
                    }
                } else if (adapter_goods.getData().get(position).getStatus().equals("3")) {
                    //已结束
                    Intent intent = new Intent(mActivity, GoodsDetailActivity.class);
                    intent.putExtra("url", adapter_goods.getData().get(position).get_links().getSelf().getHref());
                    startActivity(intent);
                } else {
                    //开抢中
                    Intent intent = new Intent(mActivity, GoodsDetailActivity.class);
                    intent.putExtra("url", adapter_goods.getData().get(position).get_links().getSelf().getHref());
                    startActivity(intent);

                }

            }

        });
    }

    @Override
    public void setTimeData(LimitTimeBean entity) {
        totalPage_time = entity.getPage().getTotalPages();
        if (totalPage_time > 0) {
            time_list = entity.get_embedded().getLimitTimeViews();
            if (null != time_list && time_list.size() > 0) {
                loadService.showSuccess();
                adapter_time.setNewData(time_list);

                int position_time = 0;

                long min_time = -1L;
                cur_time = RxTimeTool.string2Milliseconds(entity.getCurrentTime());
                long count_time;

                for (int i = 0; i < time_list.size(); i++) {
                    if (time_list.get(i).isSelected()) {
                        position_time = i;
                    }

                    if (time_list.get(i).getStatus().equals("3")) {
                        //未开抢
                        if (min_time == -1L || RxTimeTool.string2Milliseconds(entity.getCurrentTime()) < min_time) {
                            min_time = RxTimeTool.string2Milliseconds(entity.get_embedded().getLimitTimeViews().get(i).getLimitedStartTime());
                        }
                    } else if (time_list.get(i).getStatus().equals("2")) {
                        //进行中
                        if (min_time == -1L || RxTimeTool.string2Milliseconds(entity.getCurrentTime()) < min_time) {
                            min_time = RxTimeTool.string2Milliseconds(entity.get_embedded().getLimitTimeViews().get(i).getLimitedStopTime());
                        }
                    }
                }

                //用于刷新列表的倒计时时间
                count_time = min_time - cur_time;
                if (count_time > 0) {
                    initCountTime(count_time);
                }
                //状态
                status = adapter_time.getData().get(position_time).getStatus();
                oldPosition = position_time;
                if (position_time != -1) {
                    timeLimitRv.scrollToPosition(position_time);
                    LinearLayoutManager mLayoutManager =
                            (LinearLayoutManager) timeLimitRv.getLayoutManager();
                    mLayoutManager.scrollToPositionWithOffset(position_time, 0);
                }
                mPresenter.initGoodsData(cityId, adapter_time.getData().get(position_time).getLimitedStartTime(), adapter_time.getData().get(position_time).getLimitedStopTime(), page_goods, size_goods);

            } else {
                loadService.showCallback(EmptyCallback.class);//空布局回调
            }
        } else {
            loadService.showCallback(EmptyCallback.class);//空布局回调
        }
    }

    //刷新列表计时器
    private void initCountTime(final long left_time) {
        disposeTime();
        disposable_time = Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔1秒发送一条数据
                .take(left_time)
                .map(aLong -> left_time - aLong).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {

                }, throwable -> {

                }, () -> {
                    page_time = 1;
                    mPresenter.initTimeData(cityId, page_time, size_time);
                });
    }

   /* //倒计时计时器
    private void initCountDown(final long left_time) {
        disposeCount();
        disposable_count = Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔1秒发送一条数据
                .take(left_time + 1)
                .map(aLong -> left_time - aLong).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(time -> {
                    if (time > 0) {
                        limitTimer.start(time);
                    } else {
                        limitTimer.stop();
                        limitTimer.allShowZero();
                    }


                });
    }*/

    @Override
    public void setGoodsData(LimitGoodsBean entity, String startTime, String endTime) {
        //这边子类的点击事件如果使用start_time，会造成一直都是7点
        this.click_time = startTime;
        this.start_time = startTime;
        this.end_time = endTime;
        //总页数
        totalPage_goods = entity.getPage().getTotalPages();
        if (totalPage_goods <= 0) {
            //先设置空布局
            if (page_goods == 0) {
                adapter_goods.replaceData(new ArrayList<>());
                adapter_goods.setEmptyView(noDataView);
                adapter_goods.notifyDataSetChanged();
            } else {
                adapter_goods.setEmptyView(noDataView);
                adapter_goods.notifyDataSetChanged();
            }
        } else {
            goods_list = entity.get_embedded().getContent();
            if (!TextUtils.isEmpty(status)) {
                for (int i = 0; i < goods_list.size(); i++) {
                    goods_list.get(i).setStatus(status);
                }

                String time_string = adapter_time.getData().get(oldPosition).getLimitedTimeStr();
                if (status.equals("1")) {
                    //未开抢
                    if (time_string.length() > 5) {
                        //不是当天的限时购
                        limitTitle.setText("开抢预告");
                        limitTimer.setVisibility(View.GONE);
                    } else {
                        //是当天的限时购
                        limitTitle.setText("距离开抢");
                        limitTimer.setVisibility(View.VISIBLE);
                        countTime = RxTimeTool.string2Milliseconds(adapter_time.getData().get(oldPosition).getLimitedStartTime()) - cur_time;
                        limitTimer.start(countTime);
                    }
                } else if (status.equals("2")) {
                    //进行中
                    limitTitle.setText("本场还剩");
                    limitTimer.setVisibility(View.VISIBLE);
                    countTime = RxTimeTool.string2Milliseconds(adapter_time.getData().get(oldPosition).getLimitedStopTime()) - cur_time;
                    limitTimer.start(countTime);
                } else if (status.equals("3")) {
                    //已结束
                    limitTitle.setText("本场已结束");
                    limitTimer.setVisibility(View.GONE);
                }
            }
            if (page_goods == 0) {
                adapter_goods.setNewData(goods_list);
                //如果数据少 不显示已加载全部
                adapter_goods.disableLoadMoreIfNotFullPage();
            } else {
                adapter_goods.addData(goods_list);
            }
        }

        adapter_goods.loadMoreComplete();

    }

    @Override
    public void showError(String s) {
        loadService.showCallback(ErrorCallback.class);//空布局回调

    }

    @Override
    public void sendTipsSuccess(BaseResponseInfo entity) {
        dismissLoading();
        showNormal(entity.getMessage());
    }

    @Override
    public void sendTipsError(String msg) {
        dismissLoading();
    }

    @Override
    public void onLoadMoreRequested() {
        if (totalPage_goods > 0) {
            if (page_goods < totalPage_goods - 1) {
                page_goods++;
                mPresenter.initGoodsData(cityId, start_time, end_time, page_goods, size_goods);
            } else {
                adapter_goods.loadMoreEnd();
            }
        }

    }

    private void disposeTime() {
        if (disposable_time != null && !disposable_time.isDisposed()) {
            disposable_time.dispose();
        }

    }

    private void disposeCount() {
        if (disposable_count != null && !disposable_count.isDisposed()) {
            disposable_count.dispose();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposeTime();
        disposeCount();
    }

    @OnClick(R2.id.time_limit_back)
    public void backClick() {
        finish();
    }
}
